package manage

import (
	"lingc/models"
	"lingc/services"
	"lingc/utils" // 导入 common 包
	"strings"

	"github.com/gin-gonic/gin"
)

// PageAuthRule 获取所有用户
func PageAuthRule(c *gin.Context) {

	var dataRequest struct {
		Keywords string `json:"keywords" form:"keywords"`
	}
	// log.Printf("PageUser: %+v", dataRequest)

	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	where := ""
	if dataRequest.Keywords != "" {
		keyword := "'%" + dataRequest.Keywords + "%'"
		where += " (`name` like " + keyword + " or `title` like " + keyword + ")"
	}
	list, options, total, err := services.NewAuthRuleService(utils.MysqlClient).PageAuthRuleList(where)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"list": list, "options": options, "total": total})
}

// GetUser 获取用户
func GetAuthRule(c *gin.Context) {

	var dataRequest struct {
		Keyword string `json:"keyword" form:"keyword"`
	}
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	where := ""
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if dataRequest.Keyword != "" {
		keyword := "%" + dataRequest.Keyword + "%"
		where += " title like " + keyword
	}
	user, err := services.NewAuthRuleService(utils.MysqlClient).GetAuthRule(where)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// CreateUser 创建用户
func CreateAuthRule(c *gin.Context) {

	/**
	Title     string `gorm:"not null;default:'';comment:角色名称"`
	Status    uint8  `gorm:"not null;default:1;comment:0状态：0禁用，1正常"`
	Rules     string `gorm:"comment:规则ID，多个规则\",\"隔开"`
	*/
	var createRequest struct {
		Name      string `json:"name" form:"name"`
		Title     string `json:"title" form:"title"`
		URL       string `json:"url" form:"url"`
		URLParam  string `json:"url_param" form:"url_param"`
		Icon      string `json:"icon" form:"icon"`
		Type      uint8  `json:"type" form:"type"`
		APIMethod uint8  `json:"api_method" form:"api_method"`
		Rank      uint   `json:"rank" form:"rank"`
		ParentID  uint   `json:"parent_id" form:"parent_id"`
		Status    uint8  `json:"status" form:"status"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	user := &models.AuthRuleCreate{
		Name:      createRequest.Name,
		Title:     createRequest.Title,
		URL:       createRequest.URL,
		URLParam:  createRequest.URLParam,
		Icon:      createRequest.Icon,
		Type:      createRequest.Type,
		APIMethod: createRequest.APIMethod,
		Rank:      createRequest.Rank,
		ParentID:  createRequest.ParentID,
		Status:    createRequest.Status,
	}
	user, err := services.NewAuthRuleService(utils.MysqlClient).CreateAuthRule(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// UpdateUser 更新用户
func UpdateAuthRule(c *gin.Context) {
	var createRequest struct {
		ID        uint   `json:"id" form:"id"`
		Name      string `json:"name" form:"name"`
		Title     string `json:"title" form:"title"`
		URL       string `json:"url" form:"url"`
		URLParam  string `json:"url_param" form:"url_param"`
		Icon      string `json:"icon" form:"icon"`
		Type      uint8  `json:"type" form:"type"`
		APIMethod uint8  `json:"api_method" form:"api_method"`
		Rank      uint   `json:"rank" form:"rank"`
		ParentID  uint   `json:"parent_id" form:"parent_id"`
		Status    uint8  `json:"status" form:"status"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	user := &models.AuthRuleUpdate{
		ID:        createRequest.ID,
		Name:      createRequest.Name,
		Title:     createRequest.Title,
		URL:       createRequest.URL,
		URLParam:  createRequest.URLParam,
		Icon:      createRequest.Icon,
		Type:      createRequest.Type,
		APIMethod: createRequest.APIMethod,
		Rank:      createRequest.Rank,
		ParentID:  createRequest.ParentID,
		Status:    createRequest.Status,
	}
	user, err := services.NewAuthRuleService(utils.MysqlClient).UpdateAuthRule(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// DeleteUser 删除用户
func DeleteAuthRule(c *gin.Context) {
	var createRequest struct {
		ID  uint   `json:"id" form:"id"`
		IDs string `json:"ids" form:"ids"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID == 0 && len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID != 0 {
		if err := services.NewAuthRuleService(utils.MysqlClient).DeleteAuthRule(createRequest.ID); err != nil {
			utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
			return
		}
	}
	if len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	idStrs := strings.Split(createRequest.IDs, ",")
	var ids []string
	for _, idStr := range idStrs {
		idStr = strings.TrimSpace(idStr)
		if idStr == "" {
			continue
		}
		ids = append(ids, idStr)
	}
	// Convert IDs slice to a format suitable for batch deletion
	if len(ids) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "No valid IDs provided"})
		return
	}
	if err := services.NewAuthRuleService(utils.MysqlClient).DeleteAuthRules(ids); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	// ... 这里添加删除用户的逻辑 ...
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"msg": "Delete user"})
}
